from typing import Dict, Any
from .tool_registry import tool_registry, ToolMeta


class Scheduler:
    """调度引擎：负责工具调用的参数校验和执行"""

    def __init__(self):
        self._registry = tool_registry

    def _validate_parameters(self, tool_meta: ToolMeta, params: Dict[str, Any]) -> None:
        """校验参数是否符合工具定义"""
        # 检查必填参数
        for param in tool_meta.parameters:
            if param.get("required", False) and param["name"] not in params:
                raise ValueError(
                    f"工具{tool_meta.tool_id}缺少必填参数: {param['name']}（{param['desc']}）"
                )
        # 检查参数类型
        for param_name, value in params.items():
            for p in tool_meta.parameters:
                if p["name"] == param_name:
                    expected_type = p["type"]
                    actual_type = type(value).__name__
                    if expected_type != actual_type:
                        raise TypeError(
                            f"参数{param_name}类型错误: 期望{expected_type}，实际{actual_type}"
                        )
                    break

    def execute(self, tool_id: str, params: Dict[str, Any]) -> str:
        """执行工具调用并返回结果"""
        # 1. 获取工具元信息
        tool_meta = self._registry.get_tool(tool_id)

        # 2. 参数校验
        self._validate_parameters(tool_meta, params)

        # 3. 执行工具函数
        try:
            result = tool_meta.func(**params)
        except Exception as e:
            return f"❌ 工具执行失败: {str(e)}"

        # 4. 格式化结果
        return f"✅ 工具[{tool_meta.name}]结果:\n{result}"


# 全局调度实例
scheduler = Scheduler()